package cn.hinglo.permission.config.interceptor;

import cn.hinglo.baseservice.interceptors.BaseLoginInterceptor;
import cn.hinglo.common.constant.SystemConstant;
import cn.hinglo.common.enums.ExceptionEnum;
import cn.hinglo.common.utils.JwtUtil;
import cn.hinglo.common.utils.ResultUtils;
import io.jsonwebtoken.Claims;
import org.springframework.web.method.HandlerMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;


/**
 * @author HingLo
 * @createTime: 2018/11/16 11:46
 * @description: 登录拦截器
 */
public class LoginInterceptor extends BaseLoginInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler, HandlerMethod handlerMethod)
            throws Exception {
        String authHeader = request.getHeader(SystemConstant.AUTHORIZATION);
        if (authHeader == null || !authHeader.startsWith(SystemConstant.REQUEST_PREFIX)) {
            ResultUtils.error(response, ExceptionEnum.HEADERERROR);
            return false;
        } else {
            // 取得token
            try {
                String token = authHeader.substring(SystemConstant.REQUEST_PREFIX.length());
                // 检测token是否有效
                Claims claims = JwtUtil.parseJWT(token);
                // 其他详细认证处理 需要使用subject 与 UserId
                response.setHeader(SystemConstant.AUTHORIZATION, JwtUtil.createJWT(claims.getId(), claims.getSubject()));
                // ======================== 将token与userId 用户信息传入到业务层中======================
                Map<String, Object> msg = new HashMap<>(3);
                msg.put(SystemConstant.PERMISSION_USER_ID, claims.getId());
                msg.put(SystemConstant.PERMISSION_TOKEN, token);
                msg.put(SystemConstant.PERMISSION_USER_BODY, claims.getSubject());
                success(request, response, msg);

            } catch (Exception e) {
                // token 失效
                ResultUtils.error(response, ExceptionEnum.TOKENINVALID);
                return false;
            }
        }
        return true;
    }

    /***
     * 将token与userid 放入request中
     *
     * @param request 请求对象
     * @param response response
     * @param msg 发送的额外参数
     */
    @Override
    public void success(HttpServletRequest request, HttpServletResponse response, Map<String, Object> msg) {
        msg.forEach(request::setAttribute);
    }

}
